package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.TestSoulApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.*;
import com.tanhua.model.dto.TestsoulAnswersDto;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.vo.*;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2021/11/9 23:36
 */
@Service
public class TestSoulService {
    @DubboReference
    private TestSoulApi testSoulApi;

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;

    /**
     * 试卷列表
     * @return
     */
    public List<TestSoulPaperVo> paperList() {
        //多级 级联查询所有的问卷详情
        List<TestsoulPaper> paperList = testSoulApi.paperList();
        if(CollUtil.isEmpty(paperList)){
            return Collections.emptyList();
        }



        //获取当前登录用户以往的所有答题结果
        Map<Long,String> testsoulResultMap = new HashMap<>();
        List<TestsoulResult> resultList = testSoulApi.getTestsoulResultByUserId(UserHolder.getUserId());
        if(CollUtil.isNotEmpty(resultList)){
            testsoulResultMap = resultList.stream().collect(Collectors.toMap(r -> r.getPaperId(),r -> r.getResultId().toString()));
        }
        List<TestsoulQuestions> testsoulQuestions;
        List<TestsoulQuestionOptions> testsoulQuestionOptions;

        List<TestSoulPaperVo> testSoulPaperVos = new ArrayList<>();
        List<TestSoulQuestionVo> testSoulQuestionVos;
        List<TestSoulQuestionOptionVo> testSoulQuestionOptionVos;

        TestSoulPaperVo paperVo;
        TestSoulQuestionVo questionVo;
        TestSoulQuestionOptionVo optionVo;

        String unLockKey = Constants.TESTSOUL_UNLOCK_KEY + UserHolder.getUserId();
        if(redisTemplate.opsForSet().size(unLockKey) == 0){
            redisTemplate.opsForSet().add(unLockKey,"1");
        }

        //循环问卷列表，封装对应Vo列表
        for (TestsoulPaper paper:paperList){
            //试卷vo
            paperVo = new TestSoulPaperVo();
            BeanUtil.copyProperties(paper,paperVo);
            paperVo.setId(paper.getId().toString());
            //是否上锁
            Boolean isMember = redisTemplate.opsForSet().isMember(unLockKey, paper.getId().toString());
            paperVo.setIsLock(isMember?0:1);
            //最新报告id
            paperVo.setReportId(testsoulResultMap.get(paper.getId()));
            //问卷题目
            testsoulQuestions = paper.getQuestions();
            //循环题目列表，封装对应Vo列表
            if(CollUtil.isNotEmpty(testsoulQuestions)){
                testSoulQuestionVos = new ArrayList<>();
                for (TestsoulQuestions question: testsoulQuestions){
                    questionVo = new TestSoulQuestionVo();
                    questionVo.setQuestion(question.getQuestion());
                    questionVo.setId(question.getId().toString());
                    testsoulQuestionOptions = question.getOptions();
                    //循环题目选项列表，封装对应Vo列表
                    if(CollUtil.isNotEmpty(testsoulQuestionOptions)){
                        testSoulQuestionOptionVos = new ArrayList<>();
                        for (TestsoulQuestionOptions option:testsoulQuestionOptions){
                            optionVo = new TestSoulQuestionOptionVo();
                            optionVo.setId(option.getId().toString());
                            optionVo.setOption(option.getOption());
                            testSoulQuestionOptionVos.add(optionVo);
                        }
                        questionVo.setOptions(testSoulQuestionOptionVos);
                    }
                    testSoulQuestionVos.add(questionVo);
                }
                paperVo.setQuestions(testSoulQuestionVos);
            }
            testSoulPaperVos.add(paperVo);
        }
        return  testSoulPaperVos;
    }

    /**
     * 提交问卷答案
     * @param answers
     * @return
     */
    public String testSoul(Map<String, List<TestsoulAnswersDto>> answers) {
        List<TestsoulAnswersDto> answerList = answers.get("answers");
        TestsoulResult testsoulResult = this.testSoulApi.getTestsoulResultByAnswers(answerList,UserHolder.getUserId());
        if(ObjectUtil.isEmpty(testsoulResult)){
            return null;
        }
        //将已解锁的试卷id放入redis
        String unLockKey = Constants.TESTSOUL_UNLOCK_KEY + UserHolder.getUserId();
        redisTemplate.opsForSet().add(unLockKey,testsoulResult.getPaperId().toString(),testsoulResult.getNextPaperId().toString());
        return testsoulResult.getResultId().toString();
    }

    /**
     * 查看报告
     * @param id
     * @return
     */
    public TestSoulReportVo report(String id) {
        TestsoulResultDesc resultDesc = this.testSoulApi.getTestsoulResultDescById(id);
        TestSoulReportVo reportVo = new TestSoulReportVo();
        reportVo.setConclusion(resultDesc.getConclusion());
        reportVo.setCover(resultDesc.getCover());

        List<Map<String,String>> dimensions = new ArrayList<>();
        List<Map<String,Object>> similarYous = new ArrayList<>();

        Map<String,String> dimensionsMap = new HashMap<>();
        dimensionsMap.put("key","外向");
        dimensionsMap.put("value",resultDesc.getExtroversion()+"%");
        dimensions.add(dimensionsMap);

        dimensionsMap = new HashMap<>();
        dimensionsMap.put("key","判断");
        dimensionsMap.put("value",resultDesc.getEstimate()+"%");
        dimensions.add(dimensionsMap);

        dimensionsMap = new HashMap<>();
        dimensionsMap.put("key","抽象");
        dimensionsMap.put("value",resultDesc.getAbstracts()+"%");
        dimensions.add(dimensionsMap);

        dimensionsMap = new HashMap<>();
        dimensionsMap.put("key","理性");
        dimensionsMap.put("value",resultDesc.getSense()+"%");
        dimensions.add(dimensionsMap);

        reportVo.setDimensions(dimensions);

        PageResult pageResult = recommendUserApi.queryRecommendUserList(1,3,UserHolder.getUserId());
        if(CollUtil.isNotEmpty(pageResult.getItems())){
            Map<String,Object> similarYouMap;
            List<RecommendUser> recommendUsers = (List<RecommendUser>)pageResult.getItems();
            List<Long> userIds = recommendUsers.stream().map(u -> u.getUserId()).collect(Collectors.toList());
            Map<Long, UserInfo> userMap = userInfoApi.findByIds(userIds, null);
            for(RecommendUser user: recommendUsers){
                similarYouMap = new HashMap<>();
                similarYouMap.put("id",user.getUserId().intValue());
                similarYouMap.put("avatar",userMap.get(user.getUserId()).getAvatar());
                similarYous.add(similarYouMap);
            }
            reportVo.setSimilarYou(similarYous);
        }
        return reportVo;
    }
}
